package lime.xquery.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

public class XQueryParametersView extends ViewPart {

	public static final String ID = "lime.xquery.view.parameters";

	private Composite container;
	
	private Map<String, Text> widgets = new HashMap<String, Text>();;
	
	@Override
	public void createPartControl(Composite parent) {
		container = new Composite(parent, SWT.NONE);
		container.setLayout(new GridLayout(2, false));		
	}

	@Override
	public void setFocus() {
		// Empty
	}

	public void update(String xquery) {

		Map<String, String> currentParameters = getParameters();
		
		widgets.clear();
		
		for (Control control : container.getChildren()) {
			control.dispose();
		}
		
		List<String> parameters = getParameterNamesFromString(xquery);
		for (String parameter : parameters) {
			new Label(container, SWT.NONE).setText(parameter + ":");
            Text text = new Text(container, SWT.BORDER);
        
            if (currentParameters.containsKey(parameter)) {
            	text.setText(currentParameters.get(parameter));
            }
            
            text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
            widgets.put(parameter, text);
		}
		
		container.layout();
	}

	private List<String> getParameterNamesFromString(String xquery) {
		List<String> parameters = new ArrayList<String>();

		String regex = "\\$\\{(\\w*?)\\}";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(xquery);

		while (m.find()) {
			String parameter = m.group(1);
			if (StringUtils.isNotBlank(parameter) && !parameters.contains(parameter)) {
				parameters.add(parameter);
			}
		}

		return parameters;
	}

	public Map<String, String> getParameters() { 
		Map<String, String> parameters = new HashMap<String, String>();
		
		for (Entry<String, Text> entry : widgets.entrySet()) {
			String parameterName = entry.getKey();
			String parameterValue = entry.getValue().getText();
			parameters.put(parameterName, parameterValue);
		}
		
		return parameters;
	}
	
}
